package com.edg.service.impl;


import com.edg.controller.UserController;
import com.edg.dao.ClientUserMapper;
import com.edg.service.UserService;
import com.edg.utils.CodecUtils;
import com.edg.utils.CookieUtils;
import com.edg.utils.NumberUtils;
import com.edg.utils.RedisUtils;
import dao.UserMapper;
import entity.User;
import entity.UserExample;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.omg.IOP.Codec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    public static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private ClientUserMapper mapper;

    private static final String KEY_PREFIX = "user.verify";

    public int update(User user) {
        return mapper.updateByPrimaryKey(user);
    }

    public int delete(Long id) {
        return mapper.deleteByPrimaryKey(id);
    }

    public List<User> listUser() {
        return mapper.selectAll();
    }

    public User findUserById(Long id) {
        User user = (User) redisTemplate.opsForValue().get(id);
        if (user==null){
            user = mapper.selectByPrimaryKey(id);
            redisTemplate.opsForValue().set(id,user);
            return user;
        }
        return user;
    }

    @Override
    public User findUserByPhone(String phone) {
        UserExample example = new UserExample();
        example.createCriteria().andPhoneEqualTo(phone);
        return mapper.selectOneByExample(example);
    }

    @Override
    public void register(User user,String code) {
        //查询redis中的验证码
        String redisCode = (String) redisTemplate.opsForValue().get(KEY_PREFIX+user.getPhone());
        //校验验证码
        if (!StringUtils.equals(code,redisCode)){
            return;
        }
        //生成盐
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);
        //加盐加密
        user.setPwd(CodecUtils.md5Hex(user.getPwd(),salt));
        //新增用户
        mapper.insertSelective(user);
    }

    @Override
    public void sendCode(String phone) {
        if (StringUtils.isBlank(phone)) {
            return;
        }
        //生成6位数验证吗
        String code = NumberUtils.generateCode(6);
        //把验证码保存到redis,5分钟过期
        redisTemplate.opsForValue().set(KEY_PREFIX+phone,code,5,TimeUnit.MINUTES);
    }

}
